﻿using GodSoft.Common;
using GodSoft.Models;
using GodSoft.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace GodSoft.Controllers
{
    public class DeviceManagementController : BaseController
    {
        GodSoftContext _context = new GodSoftContext();
        public ActionResult GetLightComboboxList()
        {
            //总的路灯
            var SumLight = from i in _context.Lights
                           orderby i.ID
                           select i.ID;

            //控制器已经绑定的路灯
            var BindLight = from i in _context.LampControllers
                            orderby i.LightID
                            select i.LightID;
            //控制器还可以绑定的路灯
            var EnableLight = SumLight.Except(BindLight).ToList();//求差集

            var list = from i in _context.Lights
                       orderby i.ID
                       where EnableLight.Contains(i.ID)
                       select new
                       {
                           LightID = i.ID,
                           LightName = i.LightName
                       };

            return Json(list, JsonRequestBehavior.AllowGet);
        }


       public ActionResult GetControllerTypeComboboxList()
        {
            var list = from i in _context.DeviceTypes
                       orderby i.ID
                       select new
                       {
                           ControllerTypeID = i.ID,
                           ControllerTypeName = i.Type_Name
                       };

            return Json(list, JsonRequestBehavior.AllowGet);
        }

       public ActionResult GetCollectorTypeComboboxList()
       {
           var list = from i in _context.DeviceTypes
                      orderby i.ID
                      select new
                      {
                          CollectorTypeID = i.ID,
                          CollectorTypeName = i.Type_Name
                      };

           return Json(list, JsonRequestBehavior.AllowGet);
       }

       public ActionResult GetCollectorComboboxList()
        {
            var list = from i in _context.Collectors
                       orderby i.ID
                       select new
                       {
                           CollectorID = i.ID,
                           CollectorName = i.Name
                       };

            return Json(list, JsonRequestBehavior.AllowGet);
        }

       public ActionResult Index()
        {
            return View();
        }
       public ActionResult initTree()
       {
           List<DeviceManageMentTreeData> DeviceManageMentTreeDatas = new List<DeviceManageMentTreeData>();

           DeviceManageMentTreeData DeviceManageMentTreeData;
           int RowCount = 0;
           DeviceManageMentTreeData = new DeviceManageMentTreeData();
           DeviceManageMentTreeData.RowCount = RowCount;
           DeviceManageMentTreeData.ID = 0;//主键（不存在的0）
           DeviceManageMentTreeData.Name = "所有采集器";
           DeviceManageMentTreeData.ParentID = -1;
           DeviceManageMentTreeData.Url = "/Collector/Index";
           DeviceManageMentTreeData.Type = "root";
           DeviceManageMentTreeDatas.Add(DeviceManageMentTreeData);

           //采集器列表
           var list_Collector = (from i in _context.Collectors
                               select new
                               {
                                   i.ID,
                                   i.Name
                               }).ToList();

           foreach (var collector in list_Collector)
           {
               RowCount++;
               //采集器id
               int collector_id = Convert.ToInt32(collector.ID);

               DeviceManageMentTreeData = new DeviceManageMentTreeData();
               DeviceManageMentTreeData.RowCount = RowCount;
               DeviceManageMentTreeData.ID = collector_id;
               DeviceManageMentTreeData.Name = collector.Name;
               DeviceManageMentTreeData.ParentID = 0;
               //查看采集器下所有控制器
               DeviceManageMentTreeData.Url = "/LampController/index?CollectorID=" + collector_id;
               DeviceManageMentTreeData.Type = "collector";
               DeviceManageMentTreeDatas.Add(DeviceManageMentTreeData);
           }
           //控制器列表
           var list_LampController = (from i in _context.LampControllers
                                      orderby i.CollectorID      
                           select new
                           {
                               i.ID,//主键
                               i.CollectorID,//外键
                               i.Controller_Name
                           }).ToList();
           foreach (var lampcontroller in list_LampController)
           {
               RowCount++;
               //控制器id
               int lampcontroller_id = Convert.ToInt32(lampcontroller.ID);

               DeviceManageMentTreeData = new DeviceManageMentTreeData();
               DeviceManageMentTreeData.RowCount = RowCount;
               DeviceManageMentTreeData.ID = lampcontroller_id;//主键
               DeviceManageMentTreeData.FID = lampcontroller.CollectorID; //外键
               DeviceManageMentTreeData.Name = lampcontroller.Controller_Name;
               DeviceManageMentTreeData.Url = "/LampController/Index?LampControllerID=" + lampcontroller_id;
               DeviceManageMentTreeData.Type = "lampcontroller";
               DeviceManageMentTreeDatas.Add(DeviceManageMentTreeData);
           }

          
           //填充父节点编号
           var Collector = (from d in DeviceManageMentTreeDatas
                          where d.Type == "collector"
                          select new
                          {
                              d.RowCount,
                              d.ID,
                              d.FID
                          }).ToList();
           var LampController = (from d in DeviceManageMentTreeDatas
                      where d.Type == "lampcontroller"
                      select new
                      {
                          d.RowCount,
                          d.ID,
                          d.FID
                      }).ToList();


           int collector_rowcount;            //采集器编号
           int collectorid;                   //采集器主键
           int lampcontroller_rowcount;       //控制器编号
           int lampcontroller_fid;            //控制器外键(所属采集器)


           foreach (var collector in Collector)
           {
               collector_rowcount = collector.RowCount;//采集器编号
               collectorid = collector.ID;//采集器主键

               foreach (var lampcontroller in LampController)
               {
                   lampcontroller_rowcount = lampcontroller.RowCount;//控制器编号
                   lampcontroller_fid = lampcontroller.FID;//控制器外键(所属采集器)

                   if (collectorid == lampcontroller_fid)//如果该控制器属于该采集器
                   {
                       //父节点编号
                       DeviceManageMentTreeDatas.ElementAt(lampcontroller_rowcount).ParentID = collector_rowcount;

                   }
              }


           }

           return Content(AddNode(-1, 1, DeviceManageMentTreeDatas));

       }

       /// <summary>  
       /// 无限递归，生成easyui tree可用的json数据 
       /// </summary>  
       /// <param name="ParentID">父id</param>  
       /// <param name="deep">开始深度，默认为1</param>  
       /// <param name="List<DeviceManageMentTreeData>">用来生成easyui tree 的列表数据</param> 
       /// <returns></returns>  
       private string AddNode(int ParentID, int deep, List<DeviceManageMentTreeData> DeviceManageMentTreeDatas)
       {
           string str = "";
           int i = 0;

           var dvTree = from dmtd in DeviceManageMentTreeDatas
                        where dmtd.ParentID == ParentID
                        select dmtd;


           int d = deep;
           foreach (var drv in dvTree)
           {

               if (i == 0)//如果是某一层的开始，需要“[”开始  
               {
                   if (d == 1)//如果深度为1,即第一层  
                       str = "[";
                   else//否则，为第二层或更深  
                       str = ",\"children\":[";
               }

               else
                   str = str + ",";

               str = str + "{";
               str = str + "\"ID\":\"" + drv.RowCount + "\",";
               str = str + "\"text\":\"" + drv.Name + "\",";

               str = str + "\"attributes\"" + ":" + "{\"url\":\"" + drv.Url + "\",\"type\":\"" + drv.Type + "\",\"pid\":" + drv.ID + "}";
               

               str = str + AddNode(drv.RowCount, deep + 1, DeviceManageMentTreeDatas);//递归  

               str = str + "}";
               i = i + 1;

               if (dvTree.Count() == i)//如果某一层到了末尾,需要"]"结束  
                   str = str + "]";

           }

           return str;
       }

    

       public ActionResult Regist_LampController(LampController LampController)
       {
           if (LampController.CollectorID != 0)
           {
               _context.LampControllers.Add(LampController);
               _context.SaveChanges();
               return Content("OK");
           }
           else
           {
               return Content("添加数据失败，请您检查!");
           }
          
           
       }
       public ActionResult Regist_Collector(Collector Collector)
       {
               _context.Collectors.Add(Collector);
               _context.SaveChanges();
               return Content("OK");
       }
       
        [HttpPost]
       public ActionResult Delete_LampController(int?  ID)
       {
           if (ID != null)
           {
               if (_context.LampControllers.Any(i => i.ID == ID))
               {
                   LampController lampcontroller = _context.LampControllers.Find(ID);
                   _context.LampControllers.Remove(lampcontroller);
                   _context.SaveChanges();
                   return Content("OK");
               }
               else
               {
                   return Content("删除失败,不存在该条记录!");
               }
              
           }
           else
           {
               return Content("删除失败，请您检查!");
           }

       }
        [HttpPost]
       public ActionResult Delete_Collector(int?  ID)
       {
           if (ID != null)
           {
               if (_context.Collectors.Any(i => i.ID == ID))
               {
                   //获取采集器
                   Collector collector = _context.Collectors.Find(ID);
                   //删除该采集器下的所有控制器
                   if (_context.LampControllers.Any(i => i.CollectorID == ID))
                   {
                       foreach (var lampcontrollers in _context.LampControllers.Where(i => i.CollectorID == ID))
                       {
                           _context.LampControllers.Remove(lampcontrollers);
                       }
                  }

                   _context.Collectors.Remove(collector);
                   _context.SaveChanges();
                   return Content("OK");
               }
               else
               {
                   return Content("删除失败,不存在该条记录!");
               }
              
           }
           else 
           {
               return Content("删除失败，请您检查!");
           }
          
       }
        public ActionResult BindCollectorInfo(int ID)
        {
            var jsonData = from n in _context.Collectors
                           where n.ID==ID
                           orderby n.ID
                           select new 
                           {
                           n.ID,
                           n.Name,
                           n.TypeID,
                           n.IP,
                           n.Port,
                           n.Collector_Heartbeat_Packets,
                           n.Heartbeat_Interval,
                           n.Registration_Packet,
                           n.Collector_Status,
                           n.Enable,
                           n.Notes
                           };
            return Json(jsonData.First(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult UpdateCollectorInfo(Collector Collector)
        {
            _context.Collectors.Attach(Collector);
            _context.Entry<Collector>(Collector).State = EntityState.Modified;
            _context.SaveChanges();
            return Content("OK");
        }

        public ActionResult BindLampControllerInfo(int ID)
        {
            var jsonData = from n in _context.LampControllers
                           where n.ID == ID
                           orderby n.ID
                           select new
                           {
                               n.ID,
                               n.CollectorID,
                               n.ControllerTypeID,
                               n.Controller_Address,
                               n.Controller_Name,
                               n.Controller_Status,
                               n.Enable,
                               n.Notes
                           };
            return Json(jsonData.First(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult UpdateLampControllerInfo(LampController LampController)
        {
            _context.LampControllers.Attach(LampController);
            _context.Entry<LampController>(LampController).State = EntityState.Modified;
            _context.SaveChanges();
            return Content("OK");
        }
      

    }
}
